#include <57header.h>

typedef struct conn_s{
    int net_fd;
    int alive; // 1存活， 0断开链接
}conn_t;

int main(int argc,char*argv[])
{
    char *port = "8080";
    char *ip = "192.168.106.129";

    int socket_fd = socket(AF_INET, SOCK_STREAM, 0);

    struct sockaddr_in sockaddr;
    sockaddr.sin_family = AF_INET;
    sockaddr.sin_port = htons(atoi(port));
    sockaddr.sin_addr.s_addr = inet_addr(ip);

    bind(socket_fd, (struct sockaddr *)&sockaddr, sizeof(sockaddr));
    listen(socket_fd,  20);

    conn_t list[1000];
    int size = 0;
    memset(list, 0, sizeof(list));

    // 创建epoll对象
    int epoll_fd = epoll_create(1);

    // 放入监听
    struct epoll_event event;
    event.events = EPOLLIN;
    event.data.fd = socket_fd;
    epoll_ctl(epoll_fd, EPOLL_CTL_ADD, socket_fd, &event);

    while(1){

        struct epoll_event epoll_list[5];
        memset(epoll_list, 0, sizeof(epoll_list));
        int epoll_num = epoll_wait(epoll_fd, epoll_list, 5, -1);

        for(int i=0; i<epoll_num; i++){
            struct epoll_event temp = epoll_list[i];

            if(temp.data.fd == socket_fd){
                // 新链接到来
                int net_fd = accept(socket_fd, NULL, NULL);
                list[size].alive = 1;
                list[size].net_fd = net_fd;
                size++;

                // 放入监听
                struct epoll_event event;
                event.events = EPOLLIN;
                event.data.fd = net_fd;
                epoll_ctl(epoll_fd, EPOLL_CTL_ADD, net_fd, &event);
            }else{
                // 走到这, 意味着有一个客户端发信息过来
                // 读这个信息, 转发
                
                char buf[60] = {0};
                int ret = recv(temp.data.fd, buf, sizeof(buf), 0);
                if(ret == 0){
                    // 这个客户端断开链接
                    for(int j=0; j<size; j++){
                        if(list[j].net_fd == temp.data.fd && list[j].alive ==1 ){
                            // j的位置就是要关闭的链接
                            epoll_ctl(epoll_fd, EPOLL_CTL_DEL, temp.data.fd, NULL);

                            list[j].alive = 0;
                            
                            close(temp.data.fd);
                        }
                    }
                }
                // 转发数据
                for(int j=0; j<size; j++){
                    if(list[j].alive == 1 && list[j].net_fd != temp.data.fd){
                        send(list[j].net_fd, buf, sizeof(buf), 0);
                    }
                }
                
            }
        }
    }
    close(socket_fd);
    return 0;
}

